﻿#include "stdafx.h"
#include "RecordCheckTableModel.h"

//======================================================================================================================
QRecordCheckTableModel::QRecordCheckTableModel(bool isCheck, QObject * parent)
:QRecordTableModel(parent)
{
	isShowCheck = isCheck;
}

QRecordCheckTableModel::~QRecordCheckTableModel()
{

}

bool QRecordCheckTableModel::select(QString sql, bool isCheck)
{
	bool ret = QRecordTableModel::select(sql);
	listCheck.clear();
	for (int i = 0; i < dsRecords.rowCount(); i++)
	{
		listCheck.append(false);
	}
	isShowCheck = isCheck;
	return ret;
}

Qt::ItemFlags QRecordCheckTableModel::flags(const QModelIndex &index) const
{
	if (!index.isValid())
		return 0;
	int row = index.row();
	if (0 == index.column())
	{
		return isShowCheck ? Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | QRecordTableModel::flags(index) : QRecordTableModel::flags(index);
	}

	return QRecordTableModel::flags(index);
}

QVariant QRecordCheckTableModel::data(const QModelIndex &index, int role) const
{
	int row = index.row();
	int column = index.column();
	if (role == Qt::CheckStateRole && 0 == column && isShowCheck)
	{
		if (listCheck[row])
		{
			return Qt::Checked;
		}
		return Qt::Unchecked;
	}

	return QRecordTableModel::data(index, role);
}

bool QRecordCheckTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
	int row = index.row();
	if (role == Qt::CheckStateRole && 0 == index.column() && isShowCheck)
	{
		if (value == Qt::Unchecked)
		{
			listCheck[row] = false;
		}
		else
		{
			listCheck[row] = true;
		}
		return true;
	}

	return QRecordTableModel::setData(index, value, role);
}

bool QRecordCheckTableModel::getChecked(int row)
{
	if (row >= 0 && row < listCheck.count())
	{
		return listCheck.at(row);
	}
	else
	{
		return false;
	}
}

QModelIndex QRecordCheckTableModel::insertRow(QVariantList & value, bool bSeq)
{
	listCheck.append(false);
	return QRecordTableModel::insertRow(value);
}

bool QRecordCheckTableModel::deleteRow(QModelIndex index)
{
	CHK_EXP_RET(!index.isValid(), false);
	listCheck.removeAt(index.internalId());
	bool bRes = dsRecords.deleteRow(index.internalId());
	//CHK_EXP_RUN(bRes, emit dataChanged(createIndex(index.row(), 0),
	//	createIndex(index.row(), columnCount())));
	return bRes;
}

bool QRecordCheckTableModel::deleteRow(int row)
{
	listCheck.removeAt(row);
	bool bRes = dsRecords.deleteRow(row);
	//CHK_EXP_RUN(bRes, emit dataChanged(createIndex(index.row(), 0),
	//	createIndex(index.row(), columnCount())));
	return bRes;
}
